package com.travel.travel_springboot_web.service;

import com.travel.travel_springboot_web.entity.User;
import com.travel.travel_springboot_web.entity.TokenBlacklist;
import com.travel.travel_springboot_web.mapper.UserMapper;
import com.travel.travel_springboot_web.mapper.TokenBlacklistMapper;
import com.travel.travel_springboot_web.utils.JwtUtil;
import com.travel.travel_springboot_web.utils.WxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import io.jsonwebtoken.Claims;

@Service
public class UserService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private WxUtil wxUtil;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private TokenBlacklistMapper tokenBlacklistMapper;
    
    @Transactional
    public User login(String code) {
        try {
            // 获取openid
            String openid = wxUtil.getOpenid(code);
            logger.info("Got openid: {}", openid);
            
            // 查找或创建用户
            User user = userMapper.findByOpenid(openid);
            if (user == null) {
                user = new User();
                user.setOpenid(openid);
                user.setRole(1);  // 默认为顾客
                user.setStatus(1);  // 默认正常状态
                userMapper.insert(user);
                logger.info("Created new user with id: {}", user.getId());
            } else if (user.getStatus() != 1) {
                throw new RuntimeException("账号已被禁用");
            }
            
            // 生成token
            String token = jwtUtil.generateToken(user.getId(), user.getRole());
            user.setToken(token);
            
            return user;
        } catch (Exception e) {
            logger.error("Login failed: ", e);
            throw new RuntimeException("登录失败: " + e.getMessage());
        }
    }
    
    @Transactional
    public User updateProfile(User user) {
        try {
            userMapper.update(user);
            return userMapper.findByOpenid(user.getOpenid());
        } catch (Exception e) {
            logger.error("Update profile failed: ", e);
            throw new RuntimeException("更新失败: " + e.getMessage());
        }
    }
    
    @Transactional
    public void logout(String token, Long userId) {
        try {
            // 解析token获取过期时间
            Claims claims = jwtUtil.getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            
            // 添加到黑名单
            TokenBlacklist blacklist = new TokenBlacklist();
            blacklist.setToken(token);
            blacklist.setUserId(userId);
            blacklist.setExpiredAt(LocalDateTime.ofInstant(expiration.toInstant(), ZoneId.systemDefault()));
            
            tokenBlacklistMapper.insert(blacklist);
            
            // 清理过期的黑名单记录
            tokenBlacklistMapper.cleanExpired();
        } catch (Exception e) {
            logger.error("Logout failed: ", e);
            throw new RuntimeException("退出失败: " + e.getMessage());
        }
    }
    
    public User getUserInfo(Long userId) {
        try {
            User user = userMapper.findById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            
            // 出于安全考虑，清除敏感信息
            user.setPassword(null);
            
            return user;
        } catch (Exception e) {
            logger.error("Error getting user info: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }
    
    @Transactional
    public User updateUserInfo(Long userId, String name, String phone) {
        try {
            // 更新用户信息
            int result = userMapper.updateUserInfo(userId, name, phone);
            if (result <= 0) {
                throw new RuntimeException("更新用户信息失败");
            }
            
            // 返回更新后的用户信息
            return userMapper.findById(userId);
        } catch (Exception e) {
            logger.error("Update user info failed: ", e);
            throw new RuntimeException("更新用户信息失败: " + e.getMessage());
        }
    }
} 